<template>
  <div class="charts" :ref="id"></div>
</template>

<script>
/**
 * echart 公共组件封装
 * 依赖安装：npm install echarts resize-detector -S
 */
//echarts更新5.0.1版本后的引入方式
import * as echarts from 'echarts'
// 监听元素大小（尺寸）变化
import { addListener, removeListener } from 'resize-detector'
// 引入工具类（utlis）的防抖方法
import { debounce } from '@/utils/index'

export default {
  props: {
    option: {
      type: Object,
      require: true,
      default: () => {},
    },
    id: {
      type: String,
      require: true,
      default: 'chartDom',
    },
  },
  data() {
    return {}
  },
  watch: {
    option: {
      handler() {
        this.chart.setOption(this.option, true)
      },
      deep: true,
    },
  },
  created() {
    // 防抖，性能优化
    this.resizefn = debounce(this.resize, 300)
  },
  mounted() {
    this.renderCharts()
    // 监听元素尺寸变化
    addListener(this.$refs[this.id], this.resizefn)
  },
  methods: {
    // 初始化echarts
    renderCharts() {
      this.chart = echarts.init(this.$refs[this.id])
      if (this.option) {
        this.chart.setOption(this.option)
      }
      const _this = this
      // 注册点击事件
      this.chart.on('click', function (params) {
        _this.$emit('onClick', params)
      })
    },
    // resize()函数
    resize() {
      this.chart.resize()
    },
  },
  beforeDestroy() {
    // 移除监听器
    removeListener(this.$refs[this.id], this.resizefn)
    // 销毁charts实例
    this.chart.dispose()
    this.chart = null
  },
}
</script>

<style lang="less" scoped>
.charts {
  width: 100%;
  height: 500px;
}
</style>
